package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import entity.Pet;


public class PetDao extends BaseDao{
	
	Connection conn=null;
	PreparedStatement pstmt=null;
	ResultSet rs=null;
	
	public List<Pet> idList(int breed){
		List<Pet> list=new ArrayList<Pet>();
		try {
			conn=super.getConnection();
			String sql="select * from pet where breed=?";
			pstmt=conn.prepareStatement(sql);
			pstmt.setInt(1, breed);
			rs=pstmt.executeQuery();
			while (rs.next()) {
				Pet pet=new Pet();
				pet.setId(rs.getInt("id"));
				pet.setName(rs.getString("name"));
				pet.setBreed(rs.getInt("breed"));
				pet.setSex(rs.getInt("sex"));
				pet.setBirthday(rs.getString("birthday"));
				pet.setDescription(rs.getString("description"));
				list.add(pet);
			}
		}catch(Exception e){
			
		}finally {
			super.closeAll(conn, pstmt, rs);
		}
		return list;
	}
	
	
	public List<Pet> list(){
		List<Pet> list=new ArrayList<Pet>();
		try {
			conn=super.getConnection();
			String sql="SELECT * FROM pet";
			pstmt=conn.prepareStatement(sql);
			rs=pstmt.executeQuery();
			while (rs.next()) {
				Pet pet=new Pet();
				pet.setId(rs.getInt("id"));
				pet.setName(rs.getString("name"));
				pet.setBreed(rs.getInt("breed"));
				pet.setSex(rs.getInt("sex"));
				pet.setBirthday(rs.getString("birthday"));
				pet.setDescription(rs.getString("description"));
				list.add(pet);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			super.closeAll(conn, pstmt, rs);
		}
		return list;
	}
	public int petunied(String name){
		int result=0;
		try {
			conn=super.getConnection();
			String sql="select count(1) from pet where name=?";
			pstmt=conn.prepareStatement(sql);
			pstmt.setString(1, name);
			rs=pstmt.executeQuery();
			while (rs.next()) {
				result=rs.getInt(1);
				
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally {
			super.closeAll(conn, pstmt, rs);
		}
		return result;
	}
	public int add(Pet pet){
		int result=0;
		try {
			conn=super.getConnection();
			String sql="INSERT INTO pet(name, breed, sex, birthday, description) VALUES (?,?,?,?,?)";
			pstmt=conn.prepareStatement(sql);
			pstmt.setObject(1, pet.getName());
			pstmt.setObject(2, pet.getBreed());
			pstmt.setObject(3, pet.getSex());
			pstmt.setObject(4, pet.getBirthday());
			pstmt.setObject(5, pet.getDescription());
			result=pstmt.executeUpdate();
	
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			super.closeAll(conn, pstmt, rs);
		}
		return result;
	}

}
